//
//  LSBusinessTripApplyViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/1/22.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSBusinessTripApplyViewController.h"
#import "LSInfoCollectTableViewCell.h"
#import "LSDatePickViewController.h"
#import "LSBusinessTripApplyLocationTableViewCell.h"
#import "NZKTextView.h"

#define FontSize 14

@interface LSBusinessTripApplyViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *tableViewHeaderView;
@property (nonatomic, strong) UIView *tableViewFooterView;
@property (nonatomic, strong) NSMutableArray *contentArray;
@property (nonatomic, strong) NSMutableArray <NSDictionary *> *businessTripLocationArray;

@property (nonatomic, strong) NZKTextView *contentTV;
@property (nonatomic, strong) UITextField *postTF;
@property (nonatomic, strong) UITextField *businessTripFeeProviderTF;
@property (nonatomic, strong) UITextField *businessTripBeginTimeTF;
@property (nonatomic, strong) UITextField *businessTripEndTimeTF;
@property (nonatomic, strong) UITextField *businessTripMethodTF;
@property (nonatomic, strong) UITextField *businessTripTimeLengthTF;
@property (nonatomic, strong) UITextField *approveByTF;
@property (nonatomic, strong) UITextField *informToTF;
@property (nonatomic, strong) NZKTextView *remarksTV;

@property (nonatomic, assign) BOOL isHaveDian;
@end

static NSString *LSInfoCollectTableViewCellID = @"LSInfoCollectTableViewCellID";
static NSString *LSBusinessTripApplyLocationTableViewCellID = @"LSBusinessTripApplyLocationTableViewCellID";

@implementation LSBusinessTripApplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"出差申请";
    self.isHaveDian = false;
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.tableViewHeaderView;
}

#pragma mark - 提交按钮点击事件
- (void)submitButtonClick {
    if ([self.contentTV.text isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"请输入出差事由"];
        return;
    } else if ([self.businessTripTimeLengthTF.text isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"请输入出差时长"];
        return;
    } else if ([self.businessTripBeginTimeTF.text isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"请选择出差开始时间"];
        return;
    } else if ([self.businessTripEndTimeTF.text isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"请选择出差结束时间"];
        return;
    } else if ([self.approveByTF.text isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"请选择审批人"];
        return;
    } else if (![self away_startAndAway_endIsComplete] || self.businessTripLocationArray.count <= 0) {
        [MBProgressHUD showTipMessageInWindow:@"请完善出差地点"];
        return;
    }
    NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithDictionary:@{
                                                                                    @"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],
                                                                                    @"approveMain":self.contentTV.text,
                                                                                    @"away_duration":self.businessTripTimeLengthTF.text,
                                                                                    @"awayStartTime":self.businessTripBeginTimeTF.text,
                                                                                    @"awayEndTime":self.businessTripEndTimeTF.text,
                                                                                    @"approve_id":[ValidateUtils validateNull:self.approveByTF.placeholder],
                                                                                    @"approve_name":[ValidateUtils validateNull:self.approveByTF.text],
                                                                                    @"approveState":@"2"
                                                                                    }];
    if (![[ValidateUtils validateNull:self.postTF.placeholder] isEqualToString:@""]) [param setValue:[ValidateUtils validateNull:self.postTF.placeholder] forKey:@"approveDepart"];// 职务
    if ([[ValidateUtils validateNull:self.informToTF.placeholder] isEqualToString:@""]) {// 抄送人
        [param setValue:[ValidateUtils validateNull:self.informToTF.placeholder] forKey:@"sendBy"];
        [param setValue:[ValidateUtils validateNull:self.informToTF.text] forKey:@"sendName"];
    }
    if (![[ValidateUtils validateNull:self.businessTripFeeProviderTF.text] isEqualToString:@""]) [param setValue:[ValidateUtils validateNull:self.businessTripFeeProviderTF.text] forKey:@"awayMain"];// 出差费用支付单位
    if (![[ValidateUtils validateNull:self.businessTripMethodTF.text] isEqualToString:@""]) [param setValue:[ValidateUtils validateNull:self.businessTripMethodTF.text] forKey:@"awayTool"];// 交通工具
    if (![[ValidateUtils validateNull:self.remarksTV.text] isEqualToString:@""]) [param setValue:[ValidateUtils validateNull:self.remarksTV.text] forKey:@"awayRemarks"];// 备注
    if (![self away_startAndAway_endIsNil]) {
        NSMutableString *away_startStringM = [[NSMutableString alloc] initWithString:@""];
        NSMutableString *away_endStringM = [[NSMutableString alloc] initWithString:@""];
        for (NSDictionary *dict in self.businessTripLocationArray) {
            [away_startStringM appendFormat:@"%@,",dict[@"from"]];
            [away_endStringM appendFormat:@"%@,",dict[@"to"]];
        }
        NSString *away_startString = [away_startStringM substringToIndex:away_startStringM.length-1];
        NSString *away_endString = [away_endStringM substringToIndex:away_endStringM.length-1];
        [param setValue:away_startString forKey:@"away_start"];
        [param setValue:away_endString forKey:@"away_end"];
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    [NetworkUtils requestNOHandleWithMethod:@"GET" URL:BusinessTripApply param:param completionHandler:^(id responseObject, NSError *connectionError) {
        [hud hideAnimated:true];
        if (!connectionError) {
            NSNumber *status = [responseObject objectForKey:@"status"];
            if (status.integerValue == 200) {
                [MBProgressHUD showTipMessageInWindow:[ValidateUtils validateNull:[responseObject objectForKey:@"message"]]];
                WS
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.navigationController popViewControllerAnimated:true];
                });
            } else {
                [MBProgressHUD showTipMessageInWindow:[ValidateUtils validateNull:[responseObject objectForKey:@"message"]]];
            }
        } else {
            [MBProgressHUD showTipMessageInWindow:[NSString stringWithFormat:@"%@",connectionError.localizedDescription]];
        }
    }];
}

- (BOOL)away_startAndAway_endIsComplete {
    BOOL isComplete = true;
    for (NSDictionary *dict in self.businessTripLocationArray) {
        if (([dict[@"from"] isEqualToString:@""] && ![dict[@"to"] isEqualToString:@""]) || (![dict[@"from"] isEqualToString:@""] && [dict[@"to"] isEqualToString:@""])) {
            isComplete = false;
            break;
        }
    }
    return isComplete;
}

- (BOOL)away_startAndAway_endIsNil {
    BOOL isNil = true;
    for (NSDictionary *dict in self.businessTripLocationArray) {
        if (![dict[@"from"] isEqualToString:@""] || ![dict[@"to"] isEqualToString:@""]) {
            isNil = false;
            break;
        }
    }
    return isNil;
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res =YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
    int i =0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i,1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length ==0) {
            res =NO;
            break;
        }
        i++;
    }
    return res;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if (([ValidateUtils isInputRuleNotBlank:text] && ![ValidateUtils hasSpecialString:text]) || [text isEqualToString:@""]) {//当输入符合规则和退格键时允许改变输入框
        return YES;
    } else {
        if (textView == self.contentTV && (text.length == 0 || [text isEqualToString:@""])) return TRUE;
        if (textView == self.remarksTV && (text.length == 0 || [text isEqualToString:@""])) return TRUE;
        if (textView == self.contentTV && textView.text.length > 119) return FALSE;
        if (textView == self.remarksTV && textView.text.length > 119) return FALSE;
        return TRUE;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length == 0 ||  [string isEqualToString:@""]) return true;// 如果是删除字符，肯定是要通过的
    if (textField == self.businessTripFeeProviderTF && [self validateNumber:string]) return FALSE;
    if (textField.tag >= TagFoundation * 2 && [self validateNumber:string]) return FALSE;
    if (textField == self.businessTripTimeLengthTF) {
        /*
         * 不能输入.0-9以外的字符。
         * 设置输入框输入的内容格式
         * 只能有一个小数点
         * 小数点后最多能输入两位
         * 如果第一位是.则前面加上0.
         * 如果第一位是0则后面必须输入点，否则不能输入。
         */
        
        // 判断是否有小数点
        if ([textField.text containsString:@"."]) {
            self.isHaveDian = YES;
        }else{
            self.isHaveDian = NO;
        }
        if (string.length > 0) {
            //当前输入的字符
            unichar single = [string characterAtIndex:0];
            // 不能输入.0-9以外的字符
            if (!((single >= '0' && single <= '9') || single == '.'))
            {
                //            [MBProgressHUD bwm_showTitle:@"您的输入格式不正确" toView:self hideAfter:1.0];
                return NO;
            }
            
            // 只能有一个小数点
            if (self.isHaveDian && single == '.') {
                //            [MBProgressHUD bwm_showTitle:@"最多只能输入一个小数点" toView:self hideAfter:1.0];
                return NO;
            }
            
            // 如果第一位是.则前面加上0.
            if ((textField.text.length == 0) && (single == '.')) {
                textField.text = @"0";
            }
            
            // 如果第一位是0则后面必须输入点，否则不能输入。
            if ([textField.text hasPrefix:@"0"]) {
                if (textField.text.length > 1) {
                    NSString *secondStr = [textField.text substringWithRange:NSMakeRange(1, 1)];
                    if (![secondStr isEqualToString:@"."]) {
                        //                    [MBProgressHUD bwm_showTitle:@"第二个字符需要是小数点" toView:self hideAfter:1.0];
                        return NO;
                    }
                }else{
                    if (![string isEqualToString:@"."]) {
                        //                    [MBProgressHUD bwm_showTitle:@"第二个字符需要是小数点" toView:self hideAfter:1.0];
                        return NO;
                    }
                }
            }
            
            // 小数点后最多能输入两位
            if (self.isHaveDian) {
                NSRange ran = [textField.text rangeOfString:@"."];
                // 由于range.location是NSUInteger类型的，所以这里不能通过(range.location - ran.location)>2来判断
                if (range.location > ran.location) {
                    if ([textField.text pathExtension].length > 1) {
                        //                    [MBProgressHUD bwm_showTitle:@"小数点后最多有两位小数" toView:self hideAfter:1.0];
                        return NO;
                    }
                }
            }
        }
    }
    if (range.length == 1 && string.length == 0) {
        return YES;
    } else {
        //否则返回yes,不限制其他textfield
        if (textField == self.businessTripTimeLengthTF && textField.text.length >= 5) {
            textField.text = [textField.text substringToIndex:5];
            return NO;
        } else if (textField == self.businessTripFeeProviderTF && textField.text.length >= 30) {
            textField.text = [textField.text substringToIndex:30];
            return NO;
        } else if (textField == self.businessTripMethodTF && textField.text.length >= 30) {
            textField.text = [textField.text substringToIndex:30];
            return NO;
        } else if (textField == self.businessTripTimeLengthTF) {
            // do nothing
        } else {
            if (textField.text.length >= 15) {
                textField.text = [textField.text substringToIndex:15];
                return NO;
            }
        }
    }
    return YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.contentArray.count + self.businessTripLocationArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < 2 || indexPath.row > self.businessTripLocationArray.count+1) {
        LSInfoCollectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSInfoCollectTableViewCellID forIndexPath:indexPath];
        if (indexPath.row < 2) {
            if (indexPath.row == 1) {
                cell.leftLabel.textColor = hexColor(000000);
                cell.leftLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Medium" size:14];
                cell.separatorInset = UIEdgeInsetsMake(0, ScreenWidth, 0, 0);
            } else {
                cell.leftLabel.textColor = hexColor(333333);
                cell.leftLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:14];
                cell.separatorInset = UIEdgeInsetsZero;
            }
            cell.leftLabel.numberOfLines = 1;
            cell.leftLabel.text = self.contentArray[indexPath.row];
        } else if (indexPath.row > self.businessTripLocationArray.count+1) {
            cell.leftLabel.text = self.contentArray[indexPath.row-self.businessTripLocationArray.count];
            cell.leftLabel.textColor = hexColor(333333);
            cell.leftLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:14];
            cell.separatorInset = UIEdgeInsetsZero;
            if (indexPath.row == self.businessTripLocationArray.count+2 || indexPath.row == self.businessTripLocationArray.count+5) {
                cell.leftLabel.numberOfLines = 2;
            } else {
                cell.leftLabel.numberOfLines = 1;
            }
        }
        [cell.leftLabel sizeToFit];
        if (indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 1 - 2 ||
            indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 1 - 3 ||
            indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 1 - 5 ||
            indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 1 - 6 ||
            indexPath.row == 1) {
            cell.xingImageView.hidden = false;
        } else {
            cell.xingImageView.hidden = true;
        }
        
        for (UIView *subView in cell.contentView.subviews) {
            if ([subView isKindOfClass:UITextField.class]) {
                [subView removeFromSuperview];
            }
        }
        
        LSInfoCollectTableViewCell *currentCell = cell;
        if (indexPath.row == 0) {
            [currentCell.contentView addSubview:self.postTF];
            [self.postTF mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(currentCell.leftLabel.mas_right).with.offset(12);
                make.right.equalTo(currentCell.contentView.mas_right).with.offset(-15);
                make.top.equalTo(currentCell.contentView.mas_top).with.offset(8);
                make.bottom.equalTo(currentCell.contentView.mas_bottom);
            }];
        } else if (indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 8) {
            [currentCell.contentView addSubview:self.businessTripFeeProviderTF];
            [self.businessTripFeeProviderTF mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(currentCell.leftLabel.mas_right).with.offset(12);
                make.right.equalTo(currentCell.contentView.mas_right).with.offset(-15);
                make.top.equalTo(currentCell.contentView.mas_top).with.offset(8);
                make.bottom.equalTo(currentCell.contentView.mas_bottom);
            }];
        } else if (indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 7) {
            [currentCell.contentView addSubview:self.businessTripBeginTimeTF];
            [self.businessTripBeginTimeTF mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(currentCell.leftLabel.mas_right).with.offset(12);
                make.right.equalTo(currentCell.contentView.mas_right).with.offset(-15);
                make.top.equalTo(currentCell.contentView.mas_top).with.offset(8);
                make.bottom.equalTo(currentCell.contentView.mas_bottom);
            }];
        } else if (indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 6) {
            [currentCell.contentView addSubview:self.businessTripEndTimeTF];
            [self.businessTripEndTimeTF mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(currentCell.leftLabel.mas_right).with.offset(12);
                make.right.equalTo(currentCell.contentView.mas_right).with.offset(-15);
                make.top.equalTo(currentCell.contentView.mas_top).with.offset(8);
                make.bottom.equalTo(currentCell.contentView.mas_bottom);
            }];
        } else if (indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 5) {
            [currentCell.contentView addSubview:self.businessTripMethodTF];
            [self.businessTripMethodTF mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(currentCell.leftLabel.mas_right).with.offset(12);
                make.right.equalTo(currentCell.contentView.mas_right).with.offset(-15);
                make.top.equalTo(currentCell.contentView.mas_top).with.offset(8);
                make.bottom.equalTo(currentCell.contentView.mas_bottom);
            }];
        } else if (indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 4) {
            [currentCell.contentView addSubview:self.businessTripTimeLengthTF];
            [self.businessTripTimeLengthTF mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(currentCell.leftLabel.mas_right).with.offset(12);
                make.right.equalTo(currentCell.contentView.mas_right).with.offset(-15);
                make.top.equalTo(currentCell.contentView.mas_top).with.offset(8);
                make.bottom.equalTo(currentCell.contentView.mas_bottom);
            }];
        } else if (indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 3) {
            [currentCell.contentView addSubview:self.approveByTF];
            [self.approveByTF mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(currentCell.leftLabel.mas_right).with.offset(12);
                make.right.equalTo(currentCell.contentView.mas_right).with.offset(-15);
                make.top.equalTo(currentCell.contentView.mas_top).with.offset(8);
                make.bottom.equalTo(currentCell.contentView.mas_bottom);
            }];
        } else if (indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 2) {
            [currentCell.contentView addSubview:self.informToTF];
            [self.informToTF mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(currentCell.leftLabel.mas_right).with.offset(12);
                make.right.equalTo(currentCell.contentView.mas_right).with.offset(-15);
                make.top.equalTo(currentCell.contentView.mas_top).with.offset(8);
                make.bottom.equalTo(currentCell.contentView.mas_bottom);
            }];
        } else if (indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 1) {
            [currentCell.contentView addSubview:self.remarksTV];
            [self.remarksTV mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(currentCell.contentView.mas_left).with.offset(15);
                make.right.equalTo(currentCell.contentView.mas_right).with.offset(-15);
                make.top.equalTo(currentCell.leftLabel.mas_bottom).with.offset(8);
                make.bottom.equalTo(currentCell.contentView.mas_bottom).with.offset(-8);
            }];
        }
        return cell;
    } else {
        LSBusinessTripApplyLocationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSBusinessTripApplyLocationTableViewCellID forIndexPath:indexPath];
        cell.fromTF.tag = indexPath.row+TagFoundation*2;
        cell.toTF.tag = indexPath.row+TagFoundation*3;
        cell.fromTF.delegate = self;
        cell.toTF.delegate = self;
        if (indexPath.row == 2) {
            [cell.editButton setTitle:@"+增加" forState:UIControlStateNormal];
            [cell.editButton addTarget:self action:@selector(editButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        } else {
            [cell.editButton setTitle:@"删除" forState:UIControlStateNormal];
            [cell.editButton addTarget:self action:@selector(editButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        }
        return cell;
    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if (textField.tag >= TagFoundation*2 && textField.tag < TagFoundation*3) {
        NSInteger tagger = textField.tag-TagFoundation*2-2;
        NSMutableDictionary *paramM = self.businessTripLocationArray[tagger].mutableCopy;
        [paramM setValue:textField.text forKey:@"from"];
        [self.businessTripLocationArray replaceObjectAtIndex:tagger withObject:paramM.copy];
    } else if (textField.tag >= TagFoundation*3) {
        NSInteger tagger = textField.tag-TagFoundation*3-2;
        NSMutableDictionary *paramM = self.businessTripLocationArray[tagger].mutableCopy;
        [paramM setValue:textField.text forKey:@"to"];
        [self.businessTripLocationArray replaceObjectAtIndex:tagger withObject:paramM.copy];
    }
    return true;
}

- (void)editButtonClick:(UIButton *)editButton {
    NSString *buttonTitle = editButton.titleLabel.text;
    if ([buttonTitle isEqualToString:@"+增加"]) {
        [self.businessTripLocationArray addObject:@{@"from":@"",@"to":@""}];
    } else {
        [self.businessTripLocationArray removeLastObject];
    }
    [self.tableView reloadData];
}

#pragma mark - 弹窗
- (void)showSelectControllerForTextField:(UITextField *)textField WithContentArray:(NSArray <NSDictionary *> *)contentArray showCode:(NSString *)showCode requestCode:(NSString *)requestCode {
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (int i = 0; i < contentArray.count; i++) {
        [alertC addActionTarget:alertC title:contentArray[i][showCode] color:NAV_COLOR action:^(UIAlertAction *action) {
            textField.text = [ValidateUtils validateNull:contentArray[i][showCode]];
            textField.placeholder = [ValidateUtils validateNull:contentArray[i][requestCode]];
        }];
    }
    [alertC addCancelActionTarget:alertC color:NAV_COLOR title:@"取消"];
    [self presentViewController:alertC animated:true completion:nil];
}

- (void)showDateSelectControllerForTextField:(UITextField *)textField WithTitle:(NSString *)title {
    LSDatePickViewController *alertVC = [LSDatePickViewController alertControllerWithTitle:[NSString stringWithFormat:@"%@\n\n\n\n\n\n\n\n\n\n\n\n",title] message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 获取当前datePicker上面选择的时间
        NSDate *date = alertVC.datePicker.date;
        // NSLog(@"-----%@", date);
        // 创建时间格式化工具
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        if (textField == self.businessTripBeginTimeTF) {
            if (![self.businessTripEndTimeTF.text isEqualToString:@""]) {
                NSDate *endDate = [df dateFromString:self.businessTripEndTimeTF.text];
                if ([date earlierDate:endDate] == endDate) {
                    [MBProgressHUD showTipMessageInWindow:@"出差开始时间不可晚于出差结束时间"];
                    return;
                }
            }
        } else if (textField == self.businessTripEndTimeTF) {
            if (![self.businessTripBeginTimeTF.text isEqualToString:@""]) {
                NSDate *beginDate = [df dateFromString:self.businessTripBeginTimeTF.text];
                if ([date earlierDate:beginDate] == date) {
                    [MBProgressHUD showTipMessageInWindow:@"出差结束时间不可早于出差开始时间"];
                    return;
                }
            }
        }
        NSString *str = [df stringFromDate:date];
        textField.text = [NSString stringWithFormat:@"%@",str];
        textField.backgroundColor = UIColor.whiteColor;
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:okAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)requestListForTextField:(UITextField *)textField withURLString:(NSString *)URLString andParam:(NSDictionary *)param listCode:(NSString *)listCode showCode:(NSString *)showCode requestCode:(NSString *)requestCode doAppend:(BOOL)append {
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:URLString param:param completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            NSLog(@"返回数据----%@",responseObject);
            NSArray *objArray = [responseObject objectForKey:listCode];
            if (objArray && objArray.count > 0) {
                NSMutableArray *objArrayM = [[NSMutableArray alloc] initWithArray:objArray];
                if (append) [objArrayM insertObject:@{showCode : @"--请选择--",requestCode : @""} atIndex:0];
                [self showSelectControllerForTextField:textField WithContentArray:objArrayM showCode:showCode requestCode:requestCode];
            }
        } else {
            [MBProgressHUD showTipMessageInWindow:[NSString stringWithFormat:@"%@",connectionError.localizedDescription]];
        }
    }];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.postTF) {
        // 请求职务列表
        [self requestListForTextField:self.postTF withURLString:OASjzd andParam:@{@"typeGroupName":@"userDuty",@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token]} listCode:@"obj" showCode:@"typename" requestCode:@"typecode" doAppend:false];
        return false;
    } else if (textField == self.businessTripBeginTimeTF) {
        // 弹出请假开始时间选择框
        [self showDateSelectControllerForTextField:self.businessTripBeginTimeTF WithTitle:@"请选择出差开始时间"];
        return false;
    } else if (textField == self.businessTripEndTimeTF) {
        // 弹出请假结束时间选择框
        [self showDateSelectControllerForTextField:self.businessTripEndTimeTF WithTitle:@"请选择出差结束时间"];
        return false;
    } else if (textField == self.approveByTF) {
        // 请求审批人姓名列表
        [self requestListForTextField:self.approveByTF withURLString:UserList andParam:@{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token]} listCode:@"data" showCode:@"realname" requestCode:@"username" doAppend:false];
        return false;
    } else if (textField == self.informToTF) {
        // 请求抄送人姓名列表
        [self requestListForTextField:self.informToTF withURLString:UserList andParam:@{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token]} listCode:@"data" showCode:@"realname" requestCode:@"username" doAppend:true];
        return false;
    }
    return true;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.contentArray.count + self.businessTripLocationArray.count - 1) {
        return 150;
    } else if (indexPath.row == self.businessTripLocationArray.count+2 || indexPath.row == self.businessTripLocationArray.count+5) {
        return 55;
    }
    return 44;
}

- (NSMutableArray *)contentArray {
    if (!_contentArray) {
        _contentArray = [[NSMutableArray alloc] initWithArray:@[@"职务：",@"出差地点：",@"会议培训期间\n费用支付单位：",@"出差开始时间：",@"出差结束时间：",@"乘坐交通工具\n（是否带车）：",@"出差时长：",@"审批人姓名：",@"抄送人姓名：",@"备注："]];
    }
    return _contentArray;
}

- (NSMutableArray <NSDictionary *> *)businessTripLocationArray {
    if (!_businessTripLocationArray) {
        _businessTripLocationArray = [[NSMutableArray alloc] initWithArray:@[@{@"from":@"",@"to":@""}]];
    }
    return _businessTripLocationArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight)];
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.backgroundColor = hexColor(eeeeee);
        UIView *tableViewFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];
        UIButton *submitButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 30, ScreenWidth-30, 40)];
        [submitButton setTitle:@"提交" forState:UIControlStateNormal];
        [submitButton setTitleColor:hexColor(ffffff) forState:UIControlStateNormal];
        submitButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:14];
        submitButton.backgroundColor = hexColor(FDBB2C);
        submitButton.layer.cornerRadius = 4;
        submitButton.layer.masksToBounds = true;
        [submitButton addTarget:self action:@selector(submitButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [tableViewFooterView addSubview:submitButton];
        _tableView.tableFooterView = tableViewFooterView;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:LSInfoCollectTableViewCell.class forCellReuseIdentifier:LSInfoCollectTableViewCellID];
        [_tableView registerClass:LSBusinessTripApplyLocationTableViewCell.class forCellReuseIdentifier:LSBusinessTripApplyLocationTableViewCellID];
    }
    return _tableView;
}

- (UIView *)tableViewHeaderView {
    if (!_tableViewHeaderView) {
        _tableViewHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 120+35)];
        _tableViewHeaderView.backgroundColor = hexColor(ffffff);
        [_tableViewHeaderView addSubview:self.contentTV];
        UIImageView *xingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 0, 11, 35)];
        xingImageView.contentMode = UIViewContentModeCenter;
        xingImageView.image = [UIImage imageNamed:@"xinhao"];
        [_tableViewHeaderView addSubview:xingImageView];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, ScreenWidth-40, 35) andText:@"出差事由：" andTextColor:hexColor(333333) andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:14] andTextAlignment:NSTextAlignmentLeft];
        [_tableViewHeaderView addSubview:label];
    }
    return _tableViewHeaderView;
}

- (NZKTextView *)contentTV {
    if (!_contentTV) {
        _contentTV = [[NZKTextView alloc] initWithFrame:CGRectMake(15, 35, ScreenWidth-30, 120)];
        _contentTV.layer.cornerRadius = 4;
        _contentTV.layer.masksToBounds = true;
        _contentTV.layer.borderWidth = 1;
        _contentTV.layer.borderColor = UIColor.grayColor.CGColor;
        _contentTV.delegate = self;
        _contentTV.placeHolder = @"限制120字以内";
    }
    return _contentTV;
}

- (UITextField *)postTF {
    if (!_postTF) {
        _postTF = [[UITextField alloc] init];
        _postTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:FontSize];
        UIImageView *postTFRightViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44-8, 44-8)];
        postTFRightViewImageView.contentMode = UIViewContentModeCenter;
        postTFRightViewImageView.image = [UIImage imageNamed:@"kuang_xiala"];
        _postTF.rightView = postTFRightViewImageView;
        _postTF.rightViewMode = UITextFieldViewModeAlways;
        _postTF.delegate = self;
    }
    return _postTF;
}

- (UITextField *)businessTripFeeProviderTF {
    if (!_businessTripFeeProviderTF) {
        _businessTripFeeProviderTF = [[UITextField alloc] init];
        _businessTripFeeProviderTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:FontSize];
        _businessTripFeeProviderTF.delegate = self;
    }
    return _businessTripFeeProviderTF;
}

- (UITextField *)businessTripBeginTimeTF {
    if (!_businessTripBeginTimeTF) {
        _businessTripBeginTimeTF = [[UITextField alloc] init];
        _businessTripBeginTimeTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:FontSize];
        UIImageView *businessTripBeginTimeTFRightViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44-8, 44-8)];
        businessTripBeginTimeTFRightViewImageView.contentMode = UIViewContentModeCenter;
        businessTripBeginTimeTFRightViewImageView.image = [UIImage imageNamed:@"xiala"];
        _businessTripBeginTimeTF.rightView = businessTripBeginTimeTFRightViewImageView;
        _businessTripBeginTimeTF.rightViewMode = UITextFieldViewModeAlways;
        _businessTripBeginTimeTF.delegate = self;
    }
    return _businessTripBeginTimeTF;
}

- (UITextField *)businessTripEndTimeTF {
    if (!_businessTripEndTimeTF) {
        _businessTripEndTimeTF = [[UITextField alloc] init];
        _businessTripEndTimeTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:FontSize];
        UIImageView *businessTripEndTimeTFRightViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44-8, 44-8)];
        businessTripEndTimeTFRightViewImageView.contentMode = UIViewContentModeCenter;
        businessTripEndTimeTFRightViewImageView.image = [UIImage imageNamed:@"xiala"];
        _businessTripEndTimeTF.rightView = businessTripEndTimeTFRightViewImageView;
        _businessTripEndTimeTF.rightViewMode = UITextFieldViewModeAlways;
        _businessTripEndTimeTF.delegate = self;
    }
    return _businessTripEndTimeTF;
}

- (UITextField *)businessTripMethodTF {
    if (!_businessTripMethodTF) {
        _businessTripMethodTF = [[UITextField alloc] init];
        _businessTripMethodTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:FontSize];
        _businessTripMethodTF.delegate = self;
        _businessTripMethodTF.placeholder = @"例如 :火车";
    }
    return _businessTripMethodTF;
}

- (UITextField *)businessTripTimeLengthTF {
    if (!_businessTripTimeLengthTF) {
        _businessTripTimeLengthTF = [[UITextField alloc] init];
        _businessTripTimeLengthTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:FontSize];
        _businessTripTimeLengthTF.delegate = self;
        _businessTripTimeLengthTF.placeholder = @"例如1（小时）";
        _businessTripTimeLengthTF.keyboardType = UIKeyboardTypeDecimalPad;
    }
    return _businessTripTimeLengthTF;
}

- (UITextField *)approveByTF {
    if (!_approveByTF) {
        _approveByTF = [[UITextField alloc] init];
        _approveByTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:FontSize];
        UIImageView *approveByTFRightViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44-8, 44-8)];
        approveByTFRightViewImageView.contentMode = UIViewContentModeCenter;
        approveByTFRightViewImageView.image = [UIImage imageNamed:@"kuang_xiala"];
        _approveByTF.rightView = approveByTFRightViewImageView;
        _approveByTF.rightViewMode = UITextFieldViewModeAlways;
        _approveByTF.delegate = self;
    }
    return _approveByTF;
}

- (UITextField *)informToTF {
    if (!_informToTF) {
        _informToTF = [[UITextField alloc] init];
        _informToTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:FontSize];
        UIImageView *informToTFRightViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44-8, 44-8)];
        informToTFRightViewImageView.contentMode = UIViewContentModeCenter;
        informToTFRightViewImageView.image = [UIImage imageNamed:@"kuang_xiala"];
        _informToTF.rightView = informToTFRightViewImageView;
        _informToTF.rightViewMode = UITextFieldViewModeAlways;
        _informToTF.delegate = self;
    }
    return _informToTF;
}

- (NZKTextView *)remarksTV {
    if (!_remarksTV) {
        _remarksTV = [[NZKTextView alloc] init];
        _remarksTV.layer.cornerRadius = 4;
        _remarksTV.layer.masksToBounds = true;
        _remarksTV.layer.borderWidth = 1;
        _remarksTV.layer.borderColor = UIColor.grayColor.CGColor;
        _remarksTV.delegate = self;
        _remarksTV.placeHolder = @"限制120字以内";
    }
    return _remarksTV;
}

@end
